package com.example.examwlxy.playwright;

import java.util.List;
import java.util.concurrent.*;
import java.util.function.Consumer;

/**
 * 线程执行器，支持按指定延迟顺序启动任务
 */
public class SequentialDelayExecutor {
    private final ScheduledExecutorService scheduler;
    private final int threadCount;
    private final long delayMillis;

    /**
     * 构造函数
     * @param threadCount 线程池大小
     * @param delayMillis 每个任务启动的延迟时间（毫秒）
     */
    public SequentialDelayExecutor(int threadCount, long delayMillis) {
        this.threadCount = threadCount;
        this.delayMillis = delayMillis;
        this.scheduler = Executors.newScheduledThreadPool(1);
    }

    /**
     * 按顺序延迟执行多个任务
     * @param tasks 要执行的任务列表
     * @throws InterruptedException 如果执行被中断
     */
    public void executeTasksWithDelay(List<Runnable> tasks) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(tasks.size());
        ExecutorService taskExecutor = Executors.newFixedThreadPool(threadCount);

        for (int i = 0; i < tasks.size(); i++) {
            final int index = i;
            scheduler.schedule(() -> {
                taskExecutor.submit(() -> {
                    try {
                        System.out.printf("任务 %d 开始执行 (线程: %s)%n",
                                index + 1, Thread.currentThread().getName());
                        tasks.get(index).run();
                    } catch (Exception e) {
                        System.err.printf("任务 %d 执行失败: %s%n", index + 1, e.getMessage());
                    } finally {
                        latch.countDown();
                    }
                });
            }, i * delayMillis, TimeUnit.MILLISECONDS);
        }

        // 等待所有任务完成
        latch.await();

        // 关闭线程池
        taskExecutor.shutdown();
        scheduler.shutdown();
    }
}